import React, {useContext, useEffect, useState} from 'react';
import {
    ActivityIndicator,
    Alert,
    Dimensions,
    ImageBackground,
    Platform, RefreshControl,
    ScrollView, StyleSheet,
    TextInput, TouchableOpacity,
    View
} from 'react-native';
import {CheckBox, Divider, Input, ListItem, Text} from 'react-native-elements';

import LocaleContext from '../libs/locale';

import WalletContext from "../libs/wallet";
import {constansts} from "../libs/constansts";
import AsyncStorage from "@react-native-async-storage/async-storage";
import {getTxs, getTxs_Ip, SaveMyID} from "../libs/nodes";
import SimpleToast from "react-native-simple-toast";
import BouncyCheckbox from "react-native-bouncy-checkbox";
import {hex2Bytes, hex2Bytes_Random, keyPairFromSeed} from "../libs/keyPair";
import {convertKeyPair, convertPublicKey} from "../libs/ed2curve";
import Cp from "crypto-js";
import {formartMoney, sleep} from "../libs/helpers";
import Toast from "react-native-simple-toast";
import {TouchableHighlight} from "react-native-gesture-handler";

const {width,height,scale} = Dimensions.get("window");

const SetParams = ({ navigation }: any) => {
    const locale: any = useContext(LocaleContext);
    const wallet: any = useContext(WalletContext);
    const Title : string = locale._("MeChat_SetParams_Title");
    const [ChatNum,setChatNum] = useState(constansts.chatSearchMaxLength.toString());
    const [ChatRefTime,setChatRefTime] = useState(constansts.chatSearchFrequency.toString());
    const [ChatLongTime,setChatLongTime] = useState((constansts.chatSearchMaxTime/604800000).toString());
    const [chatGetAllMaxLength,setChatGetAllMaxLength] = useState((constansts.chatGetAllMaxLength).toString());

    //查询所有历史聊天记录
    const [showWaiting,setShowWaiting] = useState(false)
    const [progressLength,setProgressLength] = useState(0)
    const [TipInfo,setTipInfo] = useState("")

    //密信客服选择
    const [isSelected, setSelection] = useState(constansts.chatCustomer);//客服
    const [isSelected_ChatStats, setSelection_ChatStats] = useState(constansts.chatViewStats);//通讯状态

    //设置标题
    const setTitle = (titleStr:string) => {
        navigation.setOptions({title: titleStr})
    }

    useEffect(()=>{
        setTitle(Title);
        console.log(constansts.chatCustomer)
    })

    //获取存储的数据
    const getStore = async () => {
        // await AsyncStorage.setItem("@chatList","[]") ;
        let SaveList = await AsyncStorage.getItem("@chatList") || "[]";
        // console.log("主页数据："+SaveList)
        var resList: any = JSON.parse(SaveList) || [];
        // setChatList(resList);
        return resList;
    }

    const getHistory = async () => {
        var info: any = [];
        setProgressLength(0 );
        setTipInfo("正在获取网络数据……")
        for (let i = 0; i < Math.floor(constansts.chatGetAllMaxLength/12) ; i++) {
            let res = [];
            try{
                res = await getTxs(wallet.address, i);
            }catch (e) {

            }
            info.splice(12 * (i + 1) - 1, 0, ...res);
            console.log(new Date().getTime())
            var pL = progressLength;
            try {
                pL = (i*12) / constansts.chatGetAllMaxLength *0.8;
            }catch (e) {

            }
            setProgressLength(pL>0.8?0.8:pL );
            let nowGetTime = 0;
            try {
                nowGetTime = parseInt(res[res.length - 1].timestamp);
            }catch (e) {

            }

            if (info.length !== (i + 1) * 12 ) {
                setProgressLength(0.8);
                setTipInfo("正在解析网络数据……")
                break;
            }
        }
        await AsyncStorage.setItem("LastGetTime",info.length>0?info[0].timestamp.toString():(new Date().getTime() - constansts.chatSearchMaxTime).toString());
        return info;
    }

    //将得到的所有交易信息进行分类处理得到根据地址分类的数据
    const solveTran = async (info:any) => {

        const doSetpL = async (i: any, info: any) => {
            await sleep(1)
            let pL = 0.8 + (i / info.length) * 0.1;
            let pLM = Math.floor(pL * 100) / 100;
            console.log("pL=" + pLM)
            setProgressLength(pLM);
            console.log(progressLength)
        }

        //信息解密
        const decryptedInformation = (item:any) =>{
            try {
                let nacl = require("tweetnacl");
                //获取自己的公钥
                let getPublicKeyByte = () => {
                    let keyPair: any = keyPairFromSeed(wallet.seed);
                    let publicKey = keyPair.publicKey;
                    return convertPublicKey(publicKey);
                }
                //将字符串转成字节数组
                let decodeUTF8 = function (s: string) {
                    var i, d = unescape(encodeURIComponent(s)), b = new Uint8Array(d.length);
                    for (i = 0; i < d.length; i++) b[i] = d.charCodeAt(i);
                    return b;
                };
                //将字节数组转成字符串
                let encodeUTF8 = function (arr: any) {
                    var i, s = [];
                    for (i = 0; i < arr.length; i++) s.push(String.fromCharCode(arr[i]));
                    return decodeURIComponent(escape(s.join('')));
                };
                //设置随机nonce值
                nacl.setPRNG((x: any, n: any) => {
                    x = hex2Bytes_Random(n);
                })
                // 随机nonce值
                let nonceRandom = nacl.randomBytes(24);
                let DHKeyMy:any = convertKeyPair(keyPairFromSeed(wallet.seed));

                //获取他的公钥
                let data = JSON.parse(item.remarks);
                // let data :any = null;
                // console.log(`得到的数据data:${item.remarks}`)
                let pubHex:string;
                if(item.addressIn === wallet.address) //我发的消息，我将他的公钥用自己的私钥加密保存起来后面用
                {
                    var key  = Cp.enc.Utf8.parse(wallet.seed);
                    var decrypt = Cp.AES.decrypt(data.publicKey, key, {mode:Cp.mode.ECB,padding: Cp.pad.Pkcs7});
                    pubHex = Cp.enc.Utf8.stringify(decrypt).toString();
                    // console.log(`解析出来的数据：${pubHex}`)
                }
                else//他发的消息，我直接从签名那边获取他的公钥后面用
                {
                    let signRes = Cp.enc.Base64.parse(item.sign);
                    pubHex = signRes.toString().slice(-64);
                }
                let pub = hex2Bytes(pubHex);
                // console.log(`解析出来的公钥数组：${pub}`)
                let pubED = convertPublicKey(pub);
                // console.log(`解析出来的解密公钥数组：${pubED}`)
                var decryptedMessage = nacl.box.open(hex2Bytes(data.msg), nonceRandom,pubED, DHKeyMy.secretKey);
                let res = encodeUTF8(decryptedMessage)
                // console.log(`最终解析出来的数据：${res}`)
                return res;
            }catch (e) {
                // console.log(e)
                return false;
            }

        }

        //获取公钥
        const getPubKey = (item:any) => {
            let data = JSON.parse(item.remarks);
            let pubHex:string;
            if(item.addressIn === wallet.address) //我发的消息，我将他的公钥用自己的私钥加密保存起来后面用
            {
                var key  = Cp.enc.Utf8.parse(wallet.seed);
                var decrypt = Cp.AES.decrypt(data.publicKey, key, {mode:Cp.mode.ECB,padding: Cp.pad.Pkcs7});
                pubHex = Cp.enc.Utf8.stringify(decrypt).toString();
            }
            else//他发的消息，我直接从签名那边获取他的公钥后面用
            {
                let signRes = Cp.enc.Base64.parse(item.sign);
                pubHex = signRes.toString().slice(-64);
            }
            return pubHex;
        }

        var ChatListTemp = [];
        console.log("info.length="+info.length)
        for (let i = 0; i < info.length; i++) {
            await doSetpL(i, info);

            try {
                // console.log(typeof info[i].remarks)
                let remarks = JSON.parse(info[i].remarks);
                if (remarks.type !== "chat") {
                    // console.log(`try里面的continue`)
                    continue;
                }
                let remarksMsgStr = decryptedInformation(info[i]);
                if(!remarksMsgStr)
                {
                    continue;
                }
                // console.log(`remarksMsgStr:${remarksMsgStr}`)
                info[i].pubkey = getPubKey(info[i]);
                info[i].remarks = JSON.stringify({type:"chat",msg:remarksMsgStr,desc:""});
            } catch (e) {
                // console.log(`catch里面的continue`)
                continue;
            }
            // console.log(`这个显示了就不该显示continue了`);
            //本来为空就应该直接放数据进去
            if (ChatListTemp.length === 0) {
                let remarks = JSON.parse(info[i].remarks);
                let addressOut = (info[i].addressIn === wallet.address ? info[i].addressOut : info[i].addressIn);

                ChatListTemp.push({
                    pubkey:info[i].pubkey,
                    desc: addressOut.slice(0,5)+"..."+addressOut.slice(-5),
                    addressOut: addressOut,
                    info: [{sender: info[i].addressIn, msg: remarks.msg, timeStamp: info[i].timestamp}]
                });
                continue;
            }
            //有数据考虑是添加数据还是新的朋友
            for (let ii = 0; ii < ChatListTemp.length; ii++) {
                let remarks = JSON.parse(info[i].remarks);
                if (info[i].addressOut === ChatListTemp[ii].addressOut || info[i].addressIn === ChatListTemp[ii].addressOut) {
                    //后面添加信息
                    ChatListTemp[ii].info.splice(0, 0, {
                        sender: info[i].addressIn,
                        msg: remarks.msg,
                        timeStamp: info[i].timestamp
                    });
                    break;
                }
                //如果是新的朋友
                if (ii === (ChatListTemp.length - 1)) {
                    let addressOut = (info[i].addressIn === wallet.address ? info[i].addressOut : info[i].addressIn);
                    ChatListTemp.push({
                        pubkey:info[i].pubkey,
                        desc: addressOut.slice(0,5)+"..."+addressOut.slice(-5),
                        addressOut: addressOut,
                        info: [{sender: info[i].addressIn, msg: remarks.msg, timeStamp: info[i].timestamp}]
                    });
                    break;
                }

            }
            let pL = 0.8+(i/info.length)*0.1;
            console.log("pL="+pL)
            setProgressLength( Math.floor(pL * 100) / 100)
        }
        return ChatListTemp;
    }

    //设置名称
    const setListName = async (List: any) => {
        for (let i = 0; i < List.length; i++) {
            let addressOut = List[i].addressOut;
            console.log(addressOut)
            let res = await SaveMyID(addressOut, "", "1");
            let Name = res.dict.nickname || addressOut.slice(0,5)+"..."+addressOut.slice(-5);
            List[i].desc = Name;
        }
        return List;
    }

    //将分类好的数据写入数据库和渲染
    const saveMsg = async (ChatListTemp: any) => {

        const doSetpL = async (i: any, info: any) => {
            await sleep(1)
            let pL = 0.9 + (i / info.length) * 0.1;
            let pLM = Math.floor(pL * 100) / 100;
            console.log("pL=" + pLM)
            setProgressLength(pLM);
            console.log(progressLength)
        }

        let maxInfoLength = constansts.ChatInfoMaxLength;

        var resList = await getStore();//先获取数据库数据
        // console.log(`resList:${JSON.stringify(resList)}`)
        // console.log(`ChatListTemp:${JSON.stringify(ChatListTemp)}`)
        console.log("ChatListTemp.length="+ChatListTemp.length)
        for (let i = 0; i < ChatListTemp.length; i++) {
            await doSetpL(i, ChatListTemp);

            //console.log(`i=${i}`)
            //数据库数据为空直接添加
            if (resList.length === 0) {
                if(ChatListTemp[i].info.length > maxInfoLength)
                {
                    while(ChatListTemp[i].info.length <= maxInfoLength)
                    {
                        ChatListTemp[i].info.shift();
                    }
                }
                resList.push(ChatListTemp[i]);
                for(let iii = 0 ; iii < ChatListTemp[i].info.length ; iii++ )
                {
                    // console.log(`出现错误的数据${i}   ${iii}   ${JSON.stringify(ChatListTemp[i].info[iii])}`)
                    if (ChatListTemp[i].info[iii].sender !== wallet.address) {
                        resList[0].unread = (resList[0].unread || 0) + 1;
                    }
                }
                continue;
            }
            for (let ii = 0; ii < resList.length; ii++) {
                //console.log(`ii=${ii}`)
                //如果好友位里面已经有了，就可以比较数据进行添加了
                if (ChatListTemp[i].addressOut === resList[ii].addressOut) {
                    //添加数据
                    for (let iii = 0; iii < ChatListTemp[i].info.length; iii++) {
                        //console.log(`交易列表的时间戳${parseInt(ChatListTemp[i].info[iii].timeStamp)}`)

                        for (let j = 0; j < resList[ii].info.length; j++) {
                            if(parseInt(ChatListTemp[i].info[iii].timeStamp) < resList[ii].info[0].timeStamp && j===0 && resList[ii].info.length <= maxInfoLength)
                            {
                                resList[ii].show = true;
                                if (ChatListTemp[i].info[iii].sender !== wallet.address) {
                                    resList[ii].unread = (resList[ii].unread || 0) + 1;
                                }
                                resList[ii].info.splice(0, 0, ChatListTemp[i].info[iii]);
                                break;
                            }
                            if(parseInt(ChatListTemp[i].info[iii].timeStamp) == resList[ii].info[j].timeStamp)
                            {
                                resList[ii].info[j].showFalse = false ;
                                resList[ii].info[j].showTraning = false ;
                                resList[ii].info[j].hash = false ;
                            }
                            //console.log(`ChatListTemp[i].info[iii]${JSON.stringify(ChatListTemp[i].info[iii])}`)
                            if (parseInt(ChatListTemp[i].info[iii].timeStamp) > resList[ii].info[j].timeStamp && (j == (resList[ii].info.length - 1) || parseInt(ChatListTemp[i].info[iii].timeStamp) < resList[ii].info[j + 1].timeStamp)) {
                                let k = j + 1 ;
                                if(resList[ii].info.length >= maxInfoLength)
                                {
                                    resList[ii].info.shift();
                                    k--;
                                }
                                resList[ii].show = true;
                                if (ChatListTemp[i].info[iii].sender !== wallet.address) {
                                    resList[ii].unread = (resList[ii].unread || 0) + 1;
                                }
                                resList[ii].info.splice(k, 0, ChatListTemp[i].info[iii]);
                                break;
                            }
                        }
                    }
                    break;
                }
                //新的好友位
                if (ii === (resList.length - 1)) {
                    resList.splice(0, 0, ChatListTemp[i]);
                    // console.log(`新朋友添加未读${i}     ${JSON.stringify(ChatListTemp[i].info.length)}     ${JSON.stringify(ChatListTemp[i].info)}`)
                    for(let iii = 0 ; iii < ChatListTemp[i].info.length ; iii++ )
                    {
                        // console.log(`出现错误的数据${i}   ${iii}   ${JSON.stringify(ChatListTemp[i].info[iii])}`)
                        if (ChatListTemp[i].info[iii].sender !== wallet.address) {
                            resList[0].unread = (resList[0].unread || 0) + 1;
                        }
                    }
                    break;
                }
            }
            let pL = 0.9+(i/ChatListTemp.length)*0.1;
            console.log("pL="+pL)
            setProgressLength( Math.floor(pL * 100) / 100)
        }

        for (let i = 0; i < resList.length; i++) {
            for(let j = 0 ; j < resList[i].info.length ; j++)
            {
                let data = resList[i].info[j];
                if(data.hash && ((new Date().getTime())-data.timeStamp)>(2*60*1000) && data.display!==false)
                {
                    if(data.falseTime == 0)
                    {
                        data.showFalse = true ;
                        data.showTraning = false ;
                        data.hash = false ;
                    }
                    data.falseTime -= 1;
                }
                resList[i].info[j] = data;
            }
        }
        resList = await setListName(resList);
        setProgressLength(1);
        await AsyncStorage.setItem("@chatList", JSON.stringify(resList));
        // console.log(JSON.stringify(resList))
        console.log(`存储完毕`)
        // setChatList([...resList]);
        return resList;
    }

    const GetChatHistory = async () => {
        // console.log("开始获取所有历史记录")
        setShowWaiting(true);

        //获取最新交易
        var info = await getHistory();

        //将信息分类写入
        var ChatListTemp = await solveTran(info);

        //将好友列表比较并且保存
        await saveMsg(ChatListTemp);

        setShowWaiting(false)
    }

    const setCusTomer = async ( type:boolean) => {
        console.log(type)
        if(type)
        {
            let resList = await getStore();

            for(let i = 0 ; i < resList.length ; i++)
            {
                if(resList[i].customer ||resList[i].addressOut === "fPnu3VCHyKe4fX6ByMtyxLfMV5spfA2oN" )
                {
                    resList[i].customer = true;
                    resList[i].show = true;
                    resList[i].pubkey = "c8f6d9f616ca23e4b6e4ee1358ea7149dba542772fbb189a8061f8f92d7baefb";
                    // resList[i].logo = {uri:"https://wallet.smartx.one/img/logo.9a2b681a.png"};
                    break;
                }
                if(i == (resList.length-1))
                {
                    resList.splice(0,0,{pubkey:"c8f6d9f616ca23e4b6e4ee1358ea7149dba542772fbb189a8061f8f92d7baefb",addressOut:"fPnu3VCHyKe4fX6ByMtyxLfMV5spfA2oN",desc:"密信客服",logoSvg:{uri:"https://zh-hans.reactjs.org/logo-og.png"},customer:true,info:[]})
                    break;
                }
            }
            if(resList.length == 0)
            {
                resList.splice(0,0,{pubkey:"c8f6d9f616ca23e4b6e4ee1358ea7149dba542772fbb189a8061f8f92d7baefb",addressOut:"fPnu3VCHyKe4fX6ByMtyxLfMV5spfA2oN",desc:"密信客服",logoSvg:{uri:"https://zh-hans.reactjs.org/logo-og.png"},customer:true,info:[]})
            }
            console.log(`resList.length:${JSON.stringify(resList)}`)
            await AsyncStorage.setItem("@chatList",JSON.stringify(resList))
        }
        else
        {
            let resList = await getStore();
            for(let i = 0 ; i < resList.length ; i++)
            {
                if(resList[i].customer)
                {
                    resList[i].show = false;
                    break;
                }
            }
            await AsyncStorage.setItem("@chatList",JSON.stringify(resList))
        }


    }

    return (
        <View style={{flex:1,backgroundColor:"#F5F5F5",alignItems:"center"}}>
            {
                showWaiting?
                    <View style={{width:width,height:height,backgroundColor:"#F5F5F5"}}>
                        <ActivityIndicator
                            animating={true}
                            color={'lightblue'}
                            size={50}
                            style={{width:width,backgroundColor:"#FFFAFA69",marginTop:0.3*height}}
                        />
                        <Text style={{alignSelf:"center",marginTop:20}}>{formartMoney((progressLength*100).toString(),2)}% {TipInfo}</Text>
                        <View style={{backgroundColor:"#DCDCDC",width:width*0.8,height:20,borderRadius:10,marginTop:25,alignSelf:"center"}}/>
                        <View style={{backgroundColor:"#69BDF4",width:width*0.8*progressLength>20?width*0.8*progressLength:20,height:20,borderRadius:10,marginTop:-20,alignSelf:"flex-start",marginLeft:width*0.1}}/>
                    </View>:null
            }
            <ScrollView
                showsVerticalScrollIndicator={false}
                refreshControl={
                    <RefreshControl refreshing={false}  collapsable={true}/>
            }>
                <View style={{width:width*0.9,borderWidth:1,borderColor:"#FDFDFD",paddingBottom:30,backgroundColor:"white",marginTop:height*0.02,borderRadius:5,alignItems:"center"}}>
                    {/* 标题 密信设置*/}
                    <View style={{alignItems:"center",marginTop:height*0.01}}>
                        <Text style={{fontSize:width/360*18,color:"black",fontWeight:"bold"}}>
                            {locale._("MeChat_SetParams_MainTitle")}
                        </Text>
                    </View>
                    {/* 参数1 密信每次查询最大数量*/}
                    <View style={{position:"relative",flexDirection:"column",width:width*0.8,marginTop:20,paddingBottom:0,justifyContent:"flex-start"}}>
                        <Text style={{fontSize:15,fontWeight:"bold",color:"black"}}>
                            {locale._("MeChat_SetParams_Search")}
                        </Text>
                        <TextInput
                            // underlineColorAndroid={"black"}
                            keyboardType={"numeric"}
                            // errorMessage={}
                            defaultValue={ChatNum}
                            // value={ChatNum}
                            onChangeText={async (value) => {
                                // console.log(value)
                                value = value.replace(/[^\d]+/, '')
                                console.log(value)
                                if(value == "" || value == "0")
                                {
                                    return ;
                                }
                                if(parseInt(value)>1000)
                                {
                                    value = "1000" ;
                                    Toast.show(locale._("MeChat_SetParams_Toast_MaxSearch"))
                                }
                                value = parseInt(value).toString();
                                setChatNum(value);
                                console.log(value)
                                constansts.chatSearchMaxLength = parseInt(value);
                                await AsyncStorage.setItem("chatSearchMaxLength", value);
                                console.log("1")
                            }}
                            // placeholder={}

                            style={{marginTop:5,fontSize: 35,height:50,width:width*0.8,padding:0,paddingLeft:0,borderBottomWidth:1,borderBottomColor:"#F3F3F3",color:"black",fontWeight:"bold"}}
                        />
                        <Text style={{fontSize:15,position:"absolute",color:"#CBCACA",right:10,bottom:10}}>
                            {locale._("MeChat_SetParams_SearchUnit")}
                        </Text>

                    </View>
                    {/* 参数2 密信查询频率*/}
                    <View style={styles.paramsContainerStyle}>
                        <Text style={styles.paramsSmallTitle}>
                            {locale._("MeChat_SetParams_Interval")}
                        </Text>
                        <TextInput
                            // underlineColorAndroid={"black"}
                            keyboardType={"numeric"}
                            // errorMessage={}
                            defaultValue={ChatRefTime}
                            // value={ChatRefTime}
                            onChangeText={async (value) => {
                                value = value.replace(/[^\d]+/, '')
                                console.log(value)
                                if(value=="" || value=="0")
                                {
                                    return ;
                                }
                                if(parseInt(value) < 8)
                                {
                                    value = "8";
                                    SimpleToast.show(locale._("MeChat_SetParams_Toast_MinInterval"))
                                }
                                value = parseInt(value).toString()
                                setChatRefTime(value);
                                console.log(value)
                                constansts.chatSearchFrequency = parseInt(value);
                                await AsyncStorage.setItem("chatSearchFrequency", value);
                                console.log("2")
                            }}
                            // placeholder={}

                            style={styles.paramsInput}
                        />
                        <Text style={styles.paramsUnit}>
                            {locale._("MeChat_SetParams_IntervalUnit")}
                        </Text>
                    </View>
                    {/*/!* 参数3 密信查询最长时间*!/*/}
                    <View style={styles.paramsContainerStyle}>
                        <Text style={styles.paramsSmallTitle}>
                            {locale._("MeChat_SetParams_SearchTime")}
                        </Text>
                        <TextInput
                            // underlineColorAndroid={"black"}
                            keyboardType={"numeric"}
                            // errorMessage={}
                            defaultValue={ChatLongTime}
                            // value={ChatLongTime}
                            onChangeText={async (value) => {
                                value = value.replace(/[^\d]+/, '')
                                console.log(value)
                                if(value=="" || value=="0")
                                {
                                    return ;
                                }
                                if(parseInt(value) > 20)
                                {
                                    value = "20";
                                    SimpleToast.show(locale._("MeChat_SetParams_Toast_MaxSearchTime"))
                                }
                                value = parseInt(value).toString()
                                setChatLongTime(value);
                                console.log(value)
                                constansts.chatSearchMaxTime = parseInt(value)*604800000;
                                await AsyncStorage.setItem("chatSearchMaxTime", constansts.chatSearchMaxTime.toString());
                                console.log("3")
                            }}
                            // placeholder={}

                            style={styles.paramsInput}
                        />
                        <Text style={styles.paramsUnit}>
                            {locale._("MeChat_SetParams_SearchTimeUnit")}
                        </Text>
                    </View>
                </View>

                <View style={{width:width*0.9,borderWidth:1,borderColor:"#FDFDFD",paddingBottom:30,backgroundColor:"white",marginTop:height*0.03,borderRadius:5,alignItems:"center",marginBottom:30}}>
                    {/* 参数2.1 显示密信通讯状态 */}
                    <View style={styles.params2ContainerStyle}>
                        <Text style={styles.params2SmallTitle} >
                            {locale._("MeChat_SetParams_ShowStats")}
                        </Text>
                        <View style={styles.params2Choose}>
                            <TouchableOpacity style={styles.params2Select}
                                              activeOpacity={1}
                                                onPress={ async () => {
                                                    constansts.chatViewStats = !constansts.chatViewStats;
                                                    await AsyncStorage.setItem("chatViewStats", constansts.chatViewStats.toString())
                                                    setSelection_ChatStats(constansts.chatViewStats)
                                                    console.log(constansts.chatViewStats)
                                                }}>
                                <Text style={constansts.chatViewStats?styles.params2Selected:styles.params2Unselected}>
                                    {locale._("MeChat_SetParams_BTNShow")}
                                </Text>
                                <Text style={!constansts.chatViewStats?styles.params2Selected:styles.params2Unselected}>
                                    {locale._("MeChat_SetParams_BTNClose")}
                                </Text >
                            </TouchableOpacity>
                        </View>
                    </View>
                    {/* 参数2.2 添加客服 */}
                    <View style={styles.params2ContainerStyle}>
                        <Text style={styles.params2SmallTitle}>
                            {locale._("MeChat_SetParams_AddCustomer")}
                        </Text>
                        <View style={styles.params2Choose}>
                            <TouchableOpacity style={styles.params2Select}
                                                activeOpacity={1}
                                                onPress={ async () => {
                                                    constansts.chatCustomer = !constansts.chatCustomer;
                                                    await AsyncStorage.setItem("chatCustomer",constansts.chatCustomer.toString())
                                                    setSelection(constansts.chatCustomer)
                                                    await setCusTomer(constansts.chatCustomer)
                                                    console.log(constansts.chatCustomer)
                                                }}>
                                <Text style={constansts.chatCustomer?styles.params2Selected:styles.params2Unselected}>
                                    {locale._("MeChat_SetParams_BTNAdd")}
                                </Text>
                                <Text style={!constansts.chatCustomer?styles.params2Selected:styles.params2Unselected}>
                                    {locale._("MeChat_SetParams_BTNClose")}
                                </Text >
                            </TouchableOpacity>
                        </View>
                    </View>
                    {/* 参数2.3 获取所有历史记录 */}
                    <View style={styles.paramsContainerStyle} >
                        <View style={{flexDirection:"row"}}>
                            <Text style={styles.params2SmallTitle}>
                                {locale._("MeChat_SetParams_GetAllMessage")}
                            </Text>
                            <View style={{flex:1,flexDirection:"row",justifyContent:"flex-end",alignItems:"center"}}>
                                <TouchableOpacity onPress={()=>{
                                    Alert.alert(locale._("MeChat_SetParams_AlertTitle"), locale._("MeChat_SetParams_AlertMessage"), [{
                                        text: locale?._('cancel'),
                                        onPress: () => console.log("Cancel Pressed"),
                                        style: "cancel"
                                    }, {
                                        text: locale?._('ok'),
                                        onPress: async () => {
                                            await GetChatHistory();
                                        }
                                    }]);
                                 }}
                                >
                                    <Text style={{color:"#A8ACBA"}}>
                                        {locale._("MeChat_SetParams_Analyze")}
                                    </Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                        <TextInput
                            // underlineColorAndroid={"black"}
                            keyboardType={"numeric"}
                            // errorMessage={}
                            defaultValue={chatGetAllMaxLength}
                            // value={chatGetAllMaxLength}
                            onChangeText={async (value) => {
                                //后面设置查询所有历史数据条数和值的问题
                                value = value.replace(/[^\d]+/, '')
                                console.log(value)
                                if(value=="" || value=="0")
                                {
                                    return ;
                                }
                                value = parseInt(value).toString()
                                setChatGetAllMaxLength(value);
                                console.log(value)
                                constansts.chatGetAllMaxLength = parseInt(value);
                                await AsyncStorage.setItem("chatGetAllMaxLength", value);
                                console.log("2")
                            }}
                            style={styles.params2Input}
                        />
                        <Text style={styles.paramsUnit}>
                            {locale._("MeChat_SetParams_SearchUnit")}
                        </Text>
                    </View>
                </View>
            </ScrollView>
        </View>
    );
};

const styles = StyleSheet.create({
    paramsFirstStyle:{
        position:"relative",
        flexDirection:"column",
        width:width*0.8,
        marginTop:30,
        paddingBottom:0,
        justifyContent:"flex-start"
    },
    paramsContainerStyle:{
        position:"relative",
        flexDirection:"column",
        width:width*0.8,
        marginTop:12,
        paddingBottom:0,
        justifyContent:"flex-start"
    },
    paramsSmallTitle:{
        fontSize:15,
        fontWeight:"bold",
        color:"black"
    },
    paramsInput:{
        marginTop:5,
        fontSize: 35,
        height:50,
        width:width*0.8,
        padding:0,
        paddingLeft:0,
        borderBottomWidth:1,
        borderBottomColor:"#F3F3F3",
        color:"black",
        fontWeight:"bold"
    },
    paramsUnit:{
        fontSize:15,
        position:"absolute",
        color:"#CBCACA",
        right:10,
        bottom:10
    },
    params2ContainerStyle:{
        flexDirection:"row",
        width:width*0.8,
        marginTop:5,
        justifyContent:"flex-start",
        alignItems:"center",
        paddingBottom:20,
        borderBottomWidth:1,
        borderBottomColor:"#F3F3F3",
    },
    params2SmallTitle:{
        fontSize:18,
        fontWeight:"bold",
        color:"black",
    },
    params2Choose:{
        justifyContent:"flex-end",
        flexDirection:"row",
        flex:1,
        alignItems:"center",
    },
    params2Select:{
        flexDirection:"row",
        padding:3,
        marginTop:10,
        marginBottom:0,
        height:35,
        width:130,
        backgroundColor:"#F1F3F7",
        borderRadius:15
    },
    params2Selected:{
        height:29,
        fontSize:13,
        width:60,
        backgroundColor:"#fff",
        borderRadius:14.5,
        textAlign:"center",
        lineHeight:29,
        color:"#1684F0"
    },
    params2Unselected:{
        color:"#B9BCC9",
        fontSize:13,
        flex:1,
        textAlign:"center",
        lineHeight:29
    },
    params2Input:{
        marginTop:5,
        fontSize: 25,
        height:40,
        width:width*0.8,
        padding:0,
        paddingLeft:0,
        borderBottomWidth:1,
        borderBottomColor:"#F3F3F3",
        color:"black",
        fontWeight:"bold"
    }
})

export default SetParams;
